/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef SMART_SERVE_COMMON_INCLUDE_UTF8ASSEMBLER_H
#define SMART_SERVE_COMMON_INCLUDE_UTF8ASSEMBLER_H

#include <string>

namespace OHOS {
namespace SmartServe {
class Utf8Assembler {
public:
    // 处理一次piece，返回拼好的合法utf-8（可能为空）
    std::string feed(const std::string& piece)
    {
        buffer_ += piece;
        std::string valid, invalid;
        splitUtf8(buffer_, valid, invalid);
        buffer_ = invalid; // 保留不完整部分
        return valid;      // 返回拼好的部分
    }

    // 获取缓存中未完成的内容（调试用）
    std::string leftover() const
    {
        return buffer_;
    }

private:
    std::string buffer_;

    // 检查buffer，拆分成合法部分和不完整的尾部
    static void splitUtf8(const std::string& in, std::string& valid, std::string& invalid)
    {
        size_t len = in.size();
        size_t i = 0;
        while (i < len) {
            unsigned char c = static_cast<unsigned char>(in[i]);
            size_t charLen = 0;
            if (c <= 0x7F) {
                charLen = 1; // 1字节ASCII
            } else if ((c >> 5) == 0x6) {
                charLen = 2; // 110xxxxx
            } else if ((c >> 4) == 0xE) {
                charLen = 3; // 1110xxxx
            } else if ((c >> 3) == 0x1E) {
                charLen = 4; // 11110xxx
            } else {
                // 非法字节，丢弃
                i++;
                continue;
            }
            if (i + charLen <= len) {
                valid.append(in, i, charLen);
                i += charLen;
            } else {
                // 不完整的尾部
                invalid.assign(in, i, len - i);
                return;
            }
        }
        invalid.clear();
    }
};
} // namespace SmartServe
} // namespace OHOS
#endif // SMART_SERVE_COMMON_INCLUDE_UTF8ASSEMBLER_H